﻿CREATE PROCEDURE [dbo].[CustomerReturnDocInsert]
(--возврат от покупателя
	@DocDate smalldatetime,
	@DocNumber varchar(20),
	@ContragentDocDate smalldatetime, --дата чека
	@ContragentDocNumber varchar(20), --номер чека
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @DocTypeId int,	@DepartmentUserId int

SET NOCOUNT ON

IF (@ContragentDocDate Is Null) OR (@ContragentDocNumber Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF @DocNumber Is Null
BEGIN
	exec [dbo].[GetNextDocNumber] 7, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 

IF @ContragentDocDate > @DocDate
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Дата чека больше даты возврата!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], 
ContragentDocDate, ContragentDocNumber, DepartmentUserId,
[Note], [MD], [MW]) 
VALUES (@intNextId, 7, @DocDate, @DocNumber, 
@ContragentDocDate, @ContragentDocNumber, @DepartmentUserId,
@Note, @MD, @MW);
	
SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
ContragentDocDate, ContragentDocNumber, 
DepartmentUserId, Note, MD, MW 
FROM CA.Documents WHERE (Id = @intNextId)
RETURN 0